import requests
import json
import os
import pandas as pd
from quant_researcher.quant.project_tool.time_tool import get_today

DATA_DIR = f'E:\\指标数据'


def get_id_from_asset(asset):

    file_path = os.path.join(DATA_DIR, 'all_history_ohlcvm_coinmarketcap')
    file_name = os.path.join(file_path, f'all_coin_list_coinmarketcap')
    all_coin_list_df = pd.read_excel(f'{file_name}.xlsx', index_col='slug')
    id = all_coin_list_df.loc[asset, 'id']
    # coins = all_coin_list_df[all_coin_list_df['id'] == id].index[0]
    return id


def get_asset_ohlcvm_via_coinmarketcap(asset, range):
    header = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'}
    url = f'https://api.coinmarketcap.com/data-api/v3/cryptocurrency/detail/chart?id={id}&range={range}'
    a = requests.get(url, headers=header, timeout=30)
    res = json.loads(a.text)
    if 'data' not in res.keys():
        print(f'id={id}的数据无法获取, 提示{res["status"]}')
        return None
    elif a.status_code == 200 and len(res['data']) == 0:
        print(f'id={id}的数据为空无法获取')
        return None
    res_list = []
    for item in res['data']['points']:
        res_list.append([item] + res['data']['points'][item]['v'])
    df = pd.DataFrame(res_list, columns=['time_stamp', 'close', 'amount', 'market_cap', 'price_in_btc', 'circulating_supply'])
    df['circulating_supply'] = df['circulating_supply'] / df['price_in_btc']  # 取出来的circulating_supply需要换算下
    df['volume'] = df['amount'] / (df['close'])
    df['end_date'] = pd.to_datetime(df['time_stamp'], unit='s').dt.tz_localize('UTC').dt.tz_convert('+0000')
    df['end_date'] = df['end_date'].dt.strftime('%Y-%m-%d')
    df['datetime'] = pd.to_datetime(df['time_stamp'], unit='s').dt.tz_localize('UTC').dt.tz_convert('+0000')
    df['datetime'] = df['datetime'].dt.strftime('%Y-%m-%d %H:%M:%S')
    df.sort_values(by=['datetime'], inplace=True)

    # 有些数据取出来不是日频数据，需要进行整合
    temp_df_1 = df.groupby('end_date')[['time_stamp', 'close', 'market_cap', 'price_in_btc', 'circulating_supply', 'datetime']].last()
    temp_df_2 = df.groupby('end_date')[['amount', 'volume']].last()  # 因为取到的amount 和 volume 是过去24h的交易额，因此不需要加总
    new_df = pd.concat([temp_df_1, temp_df_2], axis=1)
    today = get_today(marker='with_n_dash')
    new_df = new_df[new_df.index != today]  # 今天的数据不完整，剔除掉

    print(f'id={id}的所有OHLCVM数据获取成功')


if __name__ == '__main__':
    asset = 'bitcoin'
    get_id_from_asset(asset)
    # get_asset_ohlcvm_via_coinmarketcap()